const app=getApp()
const userDB=wx.cloud.database().collection("user")
const applyDB=wx.cloud.database().collection("apply")

Page({
  data: {
    nickName:"",
    image:"",
    datalist:[],
    ifkong:false,
  },

  onLoad: function () {
    var that=this
    userDB.where({
      _openid:app.globalData.openid
    }).get({
      success:res=> {
        that.setData({
          nickName:res.data[0].nickName,
          image:res.data[0].avatarUrl,
        })
      },
      fail:res=>{
        console.log("查询数据失败",res)
      } 
    })

    //好友申请
    applyDB.where({
      receiveOpenid:app.globalData.openid
    }).get({
      success:res=>{
        console.log(app.globalData.openid)
        console.log("看以下ifkong",that.data.ifkong)
        console.log("看一下好友申请的",res)
        if(res.data.length==0){
          that.setData({
            ifkong:true,
          })
        }else{
          that.setData({
            datalist:res.data,
            ifkong:false,
          })
        }
      }
    })
  },

  //同意好友申请
  tongyi(event){
    let that=this
    var friendOpenid=event.currentTarget.dataset.sendopenid
    console.log("同意的friendOpenid",friendOpenid)

    userDB.where({
      _openid:app.globalData.openid
    }).update({
      data:{
        friend:friendOpenid,
        friendTime:Date.parse(new Date()),
      }
    })
    userDB.where({
      _openid:friendOpenid,
    }).update({
      data:{
        friend:app.globalData.openid,
        friendTime:Date.parse(new Date()),
      }
    })
    applyDB.where(_.or([{
      receiveOpenid:app.globalData.openid,
    },{
      sendopenid:friendOpenid
    }
  ])).remove().then(res=>{
      console.log(res)
    })

    wx.showToast({
      title: '同意好友申请成功',
      icon: 'succes',
      duration: 1000,
      success:function(){
        setTimeout(function(){
          wx.navigateBack({
            delta: 1
          });
        },2000);
      }
    })
  },

  //拒绝好友申请
  jujue(event){
    var friendOpenid=event.currentTarget.dataset.sendopenid
    console.log("同意的friendOpenid",friendOpenid)

    applyDB.where({
      receiveOpenid:app.globalData.openid,
      sendopenid:friendOpenid,
    }).remove().then(res=>{
      console.log(res)
    })

    wx.showToast({
      title: '拒绝好友申请成功',
      icon: 'succes',
      duration: 1000,
    })

  },

  applyfriend(){
    wx.navigateTo({
      url: '../applyfriend/applyfriend',
    })
  },

  onPullDownRefresh:function(){
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.onLoad()
    //模拟加载
    setTimeout(function(){
      //complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    },1500);
  },

})